package com.ruicar.afs.cloud.afscase.dispatch.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelAuthorizeRegion;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelRiskInfo;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelAuthorizeRegionService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelRiskInfoService;
import com.ruicar.afs.cloud.afscase.dispatch.DispatchContext;
import com.ruicar.afs.cloud.afscase.dispatch.annotation.Dispatch;
import com.ruicar.afs.cloud.afscase.dispatch.enums.DispatchTypeEnum;
import com.ruicar.afs.cloud.afscase.dispatch.service.DispatchBaseServcie;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCarInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCarStyleDetail;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseChannelInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.*;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import com.ruicar.afs.cloud.common.rules.RuleHelper;
import com.ruicar.afs.cloud.common.rules.constants.RuleRunEnum;
import com.ruicar.afs.cloud.common.rules.dto.RuleRunResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cheng.bi
 * 置顶处理
 */
@Service
@Dispatch(name = "信审置顶", group = DispatchTypeEnum.CREDIT)
public class DispatchTopService extends DispatchBaseServcie {

    @Autowired
    private CaseBaseInfoService caseBaseInfoService;
    @Autowired
    private CaseCostInfoService caseCostInfoService;
    @Autowired
    private CaseChannelInfoService infoService;
    @Autowired
    private ChannelRiskInfoService channelRiskInfoService;
    @Autowired
    private CaseCarStyleDetailService carStyleDetailInfoService;
    @Autowired
    private CaseCarInfoService caseCarInfoService;
    @Autowired
    private ChannelBaseInfoService channelBaseInfoService;
    @Autowired
    private ChannelAuthorizeRegionService regionService;

    /**
     * 分单前实际处理方法
     *
     * @param context
     */
    public void process(DispatchContext context) {
        // modify by peng jinbo 非锁定案件才可允许分单
        List<String> canProcessStatusList = new ArrayList<>();
        canProcessStatusList.add(AfsEnumUtil.key(BusinessStateInEnum.ALLOCATION));
        canProcessStatusList.add(AfsEnumUtil.key(BusinessStateInEnum.TASK_ASSIGN)); // 分配中的任务需要检查是否需要唤醒
        List<CaseBaseInfo> caseList = caseBaseInfoService.list(
                Wrappers.<CaseBaseInfo>lambdaQuery().in(CaseBaseInfo::getBusinessStateIn, canProcessStatusList)
        );
        caseList = caseList.stream().filter(caseInfo -> !WhetherEnum.YES.getCode().equals(caseInfo.getIsLock())).collect(Collectors.toList());

        context.put(KEY, caseList);
        if (caseList != null && !caseList.isEmpty()) {
            caseList.stream().filter(info -> {
                JSONObject jsonObject = new JSONObject();
                /**业务类型*/
                jsonObject.put("businessType", info.getBusinessType());
                /**车辆类型*/
                jsonObject.put("carType", info.getCarType());
                /**车辆属性*/
                jsonObject.put("carNature", info.getCarNature());
                /**运营方式*/
                jsonObject.put("operateWay", info.getOperateWay());
                /**挂靠方式*/
                jsonObject.put("affiliatedWay", info.getAffiliatedWay());
                /**贷款总额*/
                jsonObject.put("loanAmount", info.getLoanAmtRepeat());
                /**金融产品*/
                jsonObject.put("productId", String.valueOf(info.getProductId()));
                CaseChannelInfo caseChannelInfo = infoService.getOne(Wrappers.<CaseChannelInfo>query().lambda().eq(CaseChannelInfo::getApplyNo, info.getApplyNo()));
                if (ObjectUtil.isNotNull(caseChannelInfo)) {
                    /**经销商名称*/
                    jsonObject.put("dealerName", caseChannelInfo.getDealerName());
                    ChannelBaseInfo channelBaseInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda().eq(ChannelBaseInfo::getChannelCode, caseChannelInfo.getDealerNo()));
                    if (ObjectUtil.isNotNull(channelBaseInfo)) {
                        /**经销商省份*/
                        jsonObject.put("channelProvince", channelBaseInfo.getChannelProvince());
                        /**经销商城市*/
                        jsonObject.put("channelCity", channelBaseInfo.getChannelCity());
                        /**渠道归属*/
                        jsonObject.put("channelBelong", channelBaseInfo.getChannelBelong());
                        List<ChannelAuthorizeRegion> list = regionService.list(Wrappers.<ChannelAuthorizeRegion>query().lambda().eq(ChannelAuthorizeRegion::getChannelId, channelBaseInfo.getChannelId()));
                        if (list != null && !list.isEmpty()) {
                            String practicesProvince = "";
                            String practicesCity = "";
                            for (ChannelAuthorizeRegion region : list) {
                                if (IsAssignedEnum.YES.getCode().equals(region.getParentId()) && IsAssignedEnum.YES.getCode().equals(region.getIsParent())) {
                                    practicesProvince = practicesProvince + region.getCode() + ",";
                                }
                                if (IsAssignedEnum.NO.getCode().equals(region.getIsParent())) {
                                    practicesCity = practicesCity + region.getCode() + ",";
                                }
                            }
                            /**展业省份*/
                            jsonObject.put("practicesProvince", practicesProvince.substring(0, practicesProvince.length() - 1));
                            /**展业城市*/
                            jsonObject.put("practicesCity", practicesCity.substring(0, practicesCity.length() - 1));
                        }
                        ChannelRiskInfo channelRiskInfo = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfo>query().lambda()
                                .eq(StringUtils.isNotBlank(caseChannelInfo.getDealerNo()), ChannelRiskInfo::getChannelId, channelBaseInfo.getChannelId())
                                .eq(StringUtils.isNotBlank(channelBaseInfo.getBusinessType()), ChannelRiskInfo::getBusinessType, info.getBusinessType()));
                        /**优质登记*/
                        if (ObjectUtils.isNotEmpty(channelRiskInfo)) {
                            jsonObject.put("qualityGrade", channelRiskInfo.getQualityGrade());
                        }
                    }
                }
                CaseCarInfo caseCarInfo = caseCarInfoService.getOne(Wrappers.<CaseCarInfo>query().lambda().eq(CaseCarInfo::getApplyNo, info.getApplyNo()), false);
                if (ObjectUtil.isNotNull(caseCarInfo)) {
                    /**车辆级别*/
                    jsonObject.put("carBodyClass", caseCarInfo.getCarBodyClass());
                    /**车型*/
                    jsonObject.put("modelCode", caseCarInfo.getModelCode());
                    /**购车地省份*/
                    jsonObject.put("purchaseProvince", caseCarInfo.getPurchaseCity());
                    /**购车地城市*/
                    jsonObject.put("purchaseCity", caseCarInfo.getPurchaseCity());
                    /**上牌地省份*/
                    jsonObject.put("licenseProvince", caseCarInfo.getLicenseProvince());
                    /**上牌地城市*/
                    jsonObject.put("licenseCity", caseCarInfo.getLicenseCity());
                    List<CaseCarStyleDetail> cartyleDetailInfo = carStyleDetailInfoService.list(Wrappers.<CaseCarStyleDetail>query().lambda().eq(CaseCarStyleDetail::getCarId, caseCarInfo.getId()));
                    if (cartyleDetailInfo != null && !cartyleDetailInfo.isEmpty()) {
                        /**是否新能源*/
                        jsonObject.put("isGreen", cartyleDetailInfo.get(0).getIsGreen());
                        /** 资产主类*/
                        jsonObject.put("assetsClass", cartyleDetailInfo.get(0).getCarType());
                        /** 资产子类*/
                        jsonObject.put("carTypeDetail", cartyleDetailInfo.get(0).getCarTypeDetail());
                    }
                }
                /**是否网约车*/
                if (StringUtil.isNotEmpty(info.getAffiliatedWay()) && AffiliatedWayEnum.NETWORK_CAR_AFFILIATED.getCode().equals(info.getAffiliatedWay())) {
                    jsonObject.put("onlineCar", WhetherEnum.YES.getCode());
                } else {
                    jsonObject.put("onlineCar", WhetherEnum.NO.getCode());
                }
                /**附加贷金额*/
                FinCostDetails carAmtCostInfoAdd = caseCostInfoService.getOne(Wrappers.<FinCostDetails>query().lambda().eq(FinCostDetails::getApplyNo, info.getApplyNo()).eq(FinCostDetails::getCostType, CostTypeEnum.AFFIXAMT.getCode()));
                if (ObjectUtil.isNotNull(carAmtCostInfoAdd)) {
                    jsonObject.put("loanAmt", carAmtCostInfoAdd.getLoanAmt());
                }
                /**反欺诈评分*/
                jsonObject.put("antiFraudGrade", 100);
                /**决策引擎评分*/
                jsonObject.put("decisionGrade", 100);
                BigDecimal contAmt = BigDecimal.ZERO;
                BigDecimal tailPayAmt = BigDecimal.ZERO;
                BigDecimal subsidyTotalAmt = BigDecimal.ZERO;
                FinCostDetails carAmtCostInfoCar = caseCostInfoService.getOne(Wrappers.<FinCostDetails>query().lambda().eq(FinCostDetails::getApplyNo, info.getApplyNo()).eq(FinCostDetails::getCostType, CostTypeEnum.CARAMT.getCode()));
                if (ObjectUtil.isNotNull(carAmtCostInfoCar)) {
                    /**首付比例*/
                    BigDecimal downPayScale = carAmtCostInfoCar.getDownPayScale();
                    jsonObject.put("downPayScale", downPayScale);
                    /**还款方式*/
                    jsonObject.put("repayMode", carAmtCostInfoCar.getAlgorithmType());
                    contAmt = contAmt.add(Convert.toBigDecimal(carAmtCostInfoCar.getLoanAmt(), BigDecimal.ZERO));
                    tailPayAmt = contAmt.add(Convert.toBigDecimal(carAmtCostInfoCar.getTailPayAmt(), BigDecimal.ZERO));
                    subsidyTotalAmt = contAmt.add(Convert.toBigDecimal(carAmtCostInfoCar.getDiscountAmt(), BigDecimal.ZERO));
                }
                /**贴息金额*/
                jsonObject.put("tailPayAmt", tailPayAmt);
                /**尾款金额*/
                jsonObject.put("subsidyTotalAmt", subsidyTotalAmt);
                context.put(info.getId(), jsonObject);
                //调用置顶规则
                RuleRunResult result = RuleHelper.runRule(jsonObject, "approveTop", true, RuleRunEnum.SERIAL);
                return result.getHit();
            }).map(i -> {
                i.setIsStick(TopEnum.YES.getCode());
                i.setStickTime(DateUtil.date());
                return i;
            }).collect(Collectors.toList());
            if (caseList != null && !caseList.isEmpty()) {
                caseBaseInfoService.updateBatchById(caseList);
            }
        }
    }
}
